package com.hcryan.djm.service.impl;

import com.hcryan.djm.constant.FileExtension;
import com.hcryan.djm.exception.ErrorMessage;
import com.hcryan.djm.exception.TravelException;
import com.hcryan.djm.service.MinioService;
import com.hcryan.djm.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author ryanwdj
 * @since 2025/5/5
 */
@Service
@Slf4j
public class MinioServiceImpl implements MinioService {

    @Autowired
    private MinioUtil minioUtil;

    public void getImage(String objectName, HttpServletResponse response) {
        try (InputStream is = minioUtil.download(objectName)) {
            response.setContentType(getContentType(objectName));
            OutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            os.flush();
        } catch (Exception e) {
            log.error("下载失败", e);
            throw new TravelException(ErrorMessage.EXCEPTION, "下载失败");
        }
    }


    /**
     * 获取content-type
     *
     * @param objectName 文件名
     * @return
     */
    private String getContentType(String objectName) {
        String extension = objectName.substring(objectName.lastIndexOf(".") + 1);
        String lowerExtension = extension.toLowerCase();
        switch (lowerExtension) {
            case FileExtension.PNG:
                return "image/png";
            case FileExtension.JPG:
            case FileExtension.JPEG:
                return "image/jpeg";
            case FileExtension.GIF:
                return "image/gif";
            default:
                return "application/octet-stream";
        }
    }
}
